﻿Imports System.IO
Imports System.Drawing

Module PhotoUtils
    Property NormalFolder() As String = "~/Photos"
    Property ThumbnailFolder() As String = "~/Thumbnails"

    Public Sub Save(ByVal fileName As String, ByVal imageStream As Stream, ByVal normalSize As Size, Optional ByVal thumbSize As Size = Nothing)
        Dim scaledNormalImage As Image = ScaleImage(normalSize, imageStream)
        scaledNormalImage.Save(getPhysicalPath(getNormalPath(fileName)))
        If thumbSize = Nothing Then
            thumbSize = New Size(normalSize.Width * 0.5, normalSize.Height * 0.5)
        End If
        Dim scaledThumbImage As Image = ScaleImage(thumbSize, imageStream)
        scaledThumbImage.Save(getPhysicalPath(getThumbPath(fileName)))
    End Sub

    Public Function getNormalPath(ByVal fileName As String) As String
        Return NormalFolder & "/" & fileName
    End Function

    Public Function getThumbPath(ByVal fileName As String) As String
        Return ThumbnailFolder & "/" & fileName
    End Function

    Public Function getUniqueFileName(ByVal fileName As String) As String
        Return Guid.NewGuid().ToString() & Path.GetExtension(fileName)
    End Function

    Private Function getPhysicalPath(ByVal virtualPath As String) As String
        Return System.Web.HttpContext.Current.Server.MapPath(virtualPath)
    End Function

    Private Function ScaleImage(ByVal size As Size, ByVal inputStream As Stream) As Image
        Dim inputImage As Image = Image.FromStream(inputStream)
        Dim widthScale As Double = size.Width / inputImage.Width
        Dim heightScale As Double = size.Height / inputImage.Height
        Dim scale As Double = Math.Min(widthScale, heightScale)
        Dim newWidth As Integer = inputImage.Width * scale
        Dim newHeight As Integer = inputImage.Height * scale
        Return inputImage.GetThumbnailImage(newWidth, newHeight, Nothing, IntPtr.Zero)
    End Function
End Module
